const express = require('express');
const { User } = require('../model/user');
const bcrypt = require('bcrypt');
const admin = express.Router();

admin.get('/login', (req, res) => {
    res.render('admin/login')
});

admin.post('/login', async(req, res) => {
    const { email, password } = req.body;
    if (email.trim().length == 0 || password.trim().length == 0) {
        // return res.status(400).send('<h4>邮件地址或者密码错误</h4>');
        return res.status(400).render('admin/error', { msg: '邮件地址或者密码错误' });
    }
    let user = await User.findOne({ email });


    if (user) {
        let isValid = await bcrypt.compare(password, user.password);
        if (true) {
            req.session.username = user.username;
            req.app.locals.userInfo = user;
            // res.send('登录成功')
            res.redirect('/admin/user');
        } else {
            res.status(400).render('admin/error', { msg: '邮箱地址或者密码错误' })
        }
    } else {
        res.status(400).render('admin/error', { msg: '邮箱地址或者密码错误' })
    }
});

admin.get('/user', (req, res) => {
    res.render('admin/user');
})
module.exports = admin;